<template>
  <div class="article-list">
    <van-pull-refresh
      v-model="isLoading"
      @refresh="onRefresh"
      success-text="刷新成功"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        finished-text="没有更多了"
        :error.sync="error"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <!-- <van-cell v-for="(item,index) in list" :key="index" :title="item.title" /> -->
        <article-item v-for="(item,index) in list" :key="index" :article='item'></article-item>
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticleList } from "@/api/article";
import articleItem from './article-item.vue';
export default {
  components: { articleItem },
  name: "ArticleList",
  props: {
    channel: {
      type: Object,
      required: true,
    },
  },
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      timestamp: Date.now(),
      error: false,
      isLoading: false,
    };
  },
  methods: {
    async onLoad(str) {
      try {
        // 测试
        //    if(Math.random()*10>8){
        //   JSON.parse('aaa')
        // }
        const { data } = await getArticleList({
          channel_id: this.channel.id,
          timestamp: this.timestamp,
          with_top: 0,
        });
        console.log(data);
        if (str === "refresh") {
          this.list.unshift(...data.data.results);
        } else {
          this.list.push(...data.data.results);
        }

        this.loading = false;
        if (data.data.results.length < 10) {
          this.finished = true;
        } else {
          this.timestamp = data.data.pre_timestamp;
        }
      } catch (error) {
        console.log(error);
        this.error = true;
        this.loading = false;
        this.$toast.fail("获取文章失败");
      }
    },

    // 下拉刷新
    async onRefresh() {
      // 重置还原(页码 , 是否结束)
      this.finished = false;
      this.timestamp = Date.now();
      // this.list = [];
      // 重新拉取列表
      try {
        await this.onLoad("refresh");
      } catch (error) {
        console.log(error);
      }
      // 关闭下拉loading
      this.isLoading = false;
    },
  },
};
</script>

<style scoped lang="less">
.article-list {
  // 百分比单位是相对于父元素的
  // height: 100%;
  // 视口（在移动端是布局视口）单位：vw 和 vh，不受父元素影响
  // 1vw = 视口宽度的百分之一
  // 1vh = 视口高度的百分之一
  height: 79vh;
  overflow-y: auto;
}
</style>
